<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import type { Ref } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock, Promotion } from '@element-plus/icons-vue'
import type { SendCodeDTO, UserLoginDTO } from '@/api/DTO/account'
import {
  sendCodeServer,
  userLoginServer,
  userRegisterServer,
  userForgetServer
} from '@/api/server/account'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { isLoading, toggleLoading } from '@/composables/loading'
import { useCommonStore } from '@/stores'
// 基本变量定义
const userStore = useUserStore()
const router = useRouter()
const commonStore = useCommonStore()
const startCoolDown = () => {
  // 设置冷却时间为5秒
  commonStore.coolDown = commonStore.coolDown > 0 ? commonStore.coolDown : 5
  // 启动定时器，每秒减少1秒
  commonStore.coolDownInterval = setInterval(() => {
    if (commonStore.coolDown > 0) {
      commonStore.coolDown--
    } else {
      // 冷却时间结束，清除定时器
      clearInterval(commonStore.coolDownInterval)
      commonStore.removeCoolDownInterval()
      commonStore.coolDown = 0
    }
  }, 1000)
}
// 数据模型  UserLoginDTO RegisterDTO
const model: Ref<UserLoginDTO> = ref({
  username: '',
  password: '',
  rePassword: '',
  email: '',
  phone: '',
  imageBase64: '',
  code: ''
})
//0. 验证码发送 完成 2024/3/25 22：40
const sendCodeDTO: SendCodeDTO = {
  phone: '',
  email: '',
  username: ''
}
const sendCode = async (type?: string) => {
  if (type === 'phone' || type === 'email') {
    sendCodeDTO.phone = model.value.phone
    sendCodeDTO.email = model.value.email
    if (loginForms.includes(formType)) {
      await loginForm.value.validate()
    } else {
      await refundForm.value.validate()
    }
    const res: any = await sendCodeServer(sendCodeDTO)
    model.value.imageBase64 = res.data
    startCoolDown()
  } else {
    sendCodeDTO.username = model.value.username
    const res: any = await sendCodeServer(sendCodeDTO)
    model.value.imageBase64 = res.data
  }
}

//1. 登录实现
const login = async () => {
  await loginForm.value.validate()
  toggleLoading()
  try {
    const res: any = await userLoginServer(model.value)
    console.log(res.data)
    userStore.setToken(res.data.token)
    userStore.setUser(res.data.userVO)
    router.push(`/layout`)
  } catch (e) {
    /* empty */
  }
  toggleLoading()
}
//2. 注册实现
const register = async () => {
  await loginForm.value.validate()
  toggleLoading()
  try {
    await userRegisterServer(model.value)
    formType.value = loginForms[0]
  } catch (e) {
    /* empty */
  }
  toggleLoading()
}
//3. 找回密码实现
//数据模型 RefundPwdDTO 缺少密码而已，直接用上面的UserLoginDTO
const refund = async () => {
  await refundForm.value.validate()
  toggleLoading()
  try {
    await userForgetServer(model.value)
    formType.value = loginForms[0]
  } catch (e) {
    /* empty */
  }
  toggleLoading()
}
// 找回表单类型切换
// 1.手机号找回
// 2. 邮箱找回
const refundForms: Array<any> = ['refundByPhone', 'refundByEmail']
//登录表单类型切换
// 账密登录 0
// 手机登录 1
// 邮箱登录 2
// 注册 3
const loginForms: Array<any> = [
  'loginByUsername',
  'loginByPhone',
  'loginByEmail',
  'register'
]
// 表单校验规则
const rules: any = ref({})
const loginForm: any = ref(null) //绑定登录表单
const refundForm: any = ref(null)
const formType: Ref<any> = ref(loginForms[0]) // 表单类型
// 监测表单类型变化同时数据重置,校验规则重置
watch(
  formType,
  (newType) => {
    model.value = {
      username: '',
      password: '',
      rePassword: '',
      email: '',
      phone: '',
      imageBase64: '',
      code: ''
    }
    switch (newType) {
      case loginForms[0]: //loginByUsername
        rules.value = {
          username: [
            {
              required: true,
              message: '用户名不能为空',
              trigger: 'manual'
            },
            {
              pattern: /^[a-zA-Z0-9_]{6,16}$/,
              message: '用户名 6-16 为字母组合',
              trigger: 'manual'
            }
          ],
          password: [
            {
              required: true,
              message: '密码不能为空',
              trigger: 'manual'
            },
            {
              pattern: /^\S{6,20}$/,
              message: '密码为6-20位非空字符',
              trigger: 'manual'
            }
          ]
        }
        break
      case loginForms[1]: //loginByPhone
        rules.value = {
          phone: [
            {
              required: true,
              message: '手机号不能为空',
              trigger: 'manual'
            },
            {
              require: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号错误',
              trigger: 'manual'
            }
          ]
        }
        break
      case loginForms[2]: //loginByEmail
        rules.value = {
          email: [
            {
              required: true,
              message: '邮箱不能为空',
              trigger: 'manual'
            },
            {
              require: true,
              pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
              message: '邮箱错误',
              trigger: 'manual'
            }
          ]
        }
        break
      case loginForms[3]: //register
        rules.value = {
          username: [
            {
              required: true,
              message: '用户名不为空',
              trigger: 'manual'
            }
          ],
          password: [
            {
              required: true,
              message: '密码不为空',
              trigger: 'manual'
            },
            {
              pattern: /^\S{6,15}$/,
              message: '密码为6-15位非空字符',
              trigger: 'manual'
            }
          ],
          rePassword: [
            {
              required: true,
              message: '密码不为空',
              trigger: 'manual'
            },
            {
              validator: (rule: any, value: any, callback: any) => {
                if (value !== model.value.password) {
                  callback(new Error('两次输入的密码不一致'))
                } else {
                  callback()
                }
              },
              trigger: 'manual'
            }
          ]
        }
        break
      case refundForms[0]: //refundByPhone
        rules.value = {
          username: [
            {
              required: true,
              message: '用户名不能为空',
              trigger: 'manual'
            },
            {
              pattern: /^[a-zA-Z0-9_]{6,16}$/,
              message: '用户名 6-16 为字母组合',
              trigger: 'manual'
            }
          ],
          phone: [
            {
              required: true,
              message: '手机号不能为空',
              trigger: 'manual'
            },
            {
              require: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号错误',
              trigger: 'manual'
            }
          ]
        }
        break
      case refundForms[1]: //refundByEmail
        rules.value = {
          username: [
            {
              required: true,
              message: '用户名不能为空',
              trigger: 'manual'
            },
            {
              pattern: /^[a-zA-Z0-9_]{6,16}$/,
              message: '用户名 6-16 为字母组合',
              trigger: 'manual'
            }
          ],
          email: [
            {
              required: true,
              message: '邮箱不能为空',
              trigger: 'manual'
            },
            {
              require: true,
              pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
              message: '邮箱错误',
              trigger: 'manual'
            }
          ]
        }
        break
      default:
        break
    }
  },
  {
    immediate: true,
    deep: true
  }
)
//初始化操作
onMounted(() => {
  commonStore.coolDownInterval = setInterval(() => {
    if (commonStore.coolDown > 0) {
      commonStore.coolDown--
    } else {
      // 冷却时间结束，清除定时器
      clearInterval(commonStore.coolDownInterval)
      commonStore.removeCoolDownInterval()
      commonStore.coolDown = 0
    }
  }, 1000)
})
</script>

<template>
  <div class="login-page">
    <el-row class="layout">
      <el-col :span="12" class="left">
        <div class="overlay"></div>
        <img src="@/assets/logo/image.png" height="80%" width="80%"
      /></el-col>
      <!-- 分割 -->
      <el-col :span="2"></el-col>
      <el-col :span="8" class="right">
        <!-- 登录/注册表单 -->
        <el-form
          :model="model"
          :rules="rules"
          :validate-on-rule-change="false"
          ref="loginForm"
          size="large"
          class="form"
          label-width="auto"
          v-if="loginForms.includes(formType)"
        >
          <el-form-item>
            <h1 class="title">依奇笔记</h1>
          </el-form-item>
          <el-form-item
            label="账号"
            prop="username"
            v-if="formType === loginForms[0] || formType === loginForms[3]"
          >
            <el-input
              v-model="model.username"
              placeholder="请输入账号"
              :prefix-icon="User"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            v-if="formType === loginForms[0] || formType === loginForms[3]"
          >
            <el-input
              v-model="model.password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              clearable
              show-password
              type="password"
            />
          </el-form-item>

          <el-form-item
            label="重复密码"
            prop="rePassword"
            v-if="formType === loginForms[3]"
          >
            <el-input
              v-model="model.rePassword"
              placeholder="请输入重复密码"
              :prefix-icon="Lock"
              clearable
              show-password
              type="password"
            />
          </el-form-item>

          <el-form-item
            label="手机号"
            prop="phone"
            v-if="formType === loginForms[1]"
          >
            <el-input
              v-model="model.phone"
              placeholder="请输入手机号"
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
            v-if="formType === loginForms[2]"
          >
            <el-input
              v-model="model.email"
              placeholder="请输入邮箱"
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
          <el-form-item
            class="code"
            label="验证码"
            v-if="formType !== loginForms[0]"
          >
            <div class="flex">
              <el-input
                clearable
                class="code-input"
                v-model="model.code"
                :prefix-icon="Promotion"
              />

              <el-button
                type="primary"
                class="code-btn"
                @click="
                  () => {
                    if (formType === loginForms[1]) {
                      sendCode('phone')
                    } else if (formType === loginForms[2]) {
                      sendCode('email')
                    }
                  }
                "
                v-if="formType !== loginForms[3] && commonStore.coolDown === 0"
                >获取验证码</el-button
              >
              <el-button
                class="code-btn"
                type="info"
                plain
                disabled
                v-else-if="
                  formType !== loginForms[3] && commonStore.coolDown > 0
                "
                >({{ commonStore.coolDown }})s 重新发送</el-button
              >
              <el-image
                :src="model.imageBase64"
                @click="sendCode()"
                fit="cover"
                lazy
                class="code-btn"
                v-if="formType === loginForms[3]"
              >
                <template #error>
                  <div class="reGet" @click="sendCode()">寄了</div>
                </template>
              </el-image>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-link
                type="primary"
                :underline="false"
                v-if="formType !== loginForms[0] && formType !== loginForms[3]"
                @click="formType = loginForms[0]"
                >账号密码登录</el-link
              >
              <el-link
                type="primary"
                :underline="false"
                v-if="formType !== loginForms[1] && formType !== loginForms[3]"
                @click="formType = loginForms[1]"
                >手机号登录|注册</el-link
              ><el-link
                type="primary"
                :underline="false"
                v-if="formType !== loginForms[2] && formType !== loginForms[3]"
                @click="formType = loginForms[2]"
                >邮箱登录|注册</el-link
              >
            </div>
          </el-form-item>
          <el-form-item>
            <!-- 提交表单 -->
            <el-button
              type="primary"
              class="subBtn"
              v-if="formType !== loginForms[3]"
              @click="login"
              :loading="isLoading"
              :disabled="isLoading"
              >登录</el-button
            >
            <el-button
              type="primary"
              class="subBtn"
              v-if="formType === loginForms[3]"
              @click="register"
              :loading="isLoading"
              :disabled="isLoading"
              >注册</el-button
            >
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-link
                :underline="false"
                @click="
                  () => {
                    formType = loginForms[3]
                    sendCode()
                  }
                "
                v-if="formType !== loginForms[3]"
                >注册</el-link
              >
              <el-link
                :underline="false"
                @click="formType = loginForms[0]"
                v-else
                >登录</el-link
              >
              <el-link :underline="false" @click="formType = refundForms[0]"
                >忘记密码</el-link
              >
            </div>
          </el-form-item>
        </el-form>

        <!-- 重置密码表单 -->
        <el-form
          size="large"
          ref="refundForm"
          :model="model"
          :rules="rules"
          :validate-on-rule-change="false"
          class="form"
          label-width="auto"
          v-else
        >
          <el-form-item>
            <h1 class="title">依奇笔记</h1>
          </el-form-item>
          <el-form-item label="账户号" prop="username">
            <el-input
              placeholder="请输入账号"
              v-model="model.username"
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="phone"
            v-if="formType === refundForms[0]"
          >
            <el-input
              placeholder="请输入手机号"
              v-model="model.phone"
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" v-else>
            <el-input
              placeholder="请输入邮箱"
              v-model="model.email"
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
          <el-form-item class="code" label="验证码">
            <div class="flex">
              <el-input clearable class="code-input" v-model="model.code" />
              <el-button
                type="primary"
                class="code-btn"
                @click="
                  () => {
                    if (formType === refundForms[0]) {
                      sendCode('phone')
                    } else if (formType === refundForms[1]) {
                      sendCode('email')
                    }
                  }
                "
                v-if="commonStore.coolDown === 0"
                >获取验证码</el-button
              >
              <el-button
                class="code-btn"
                type="info"
                plain
                disabled
                v-else-if="commonStore.coolDown > 0"
                >({{ commonStore.coolDown }})s 重新发送</el-button
              >
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-link
                type="primary"
                :underline="false"
                v-if="formType !== refundForms[1]"
                @click="formType = refundForms[1]"
                >邮箱找回</el-link
              >
              <el-link
                type="primary"
                :underline="false"
                v-if="formType !== refundForms[0]"
                @click="formType = refundForms[0]"
                >手机号找回</el-link
              >
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="subBtn"
              v-if="formType !== loginForms[3]"
              @click="refund"
              >找回密码</el-button
            >
          </el-form-item>

          <el-form-item class="flex">
            <div class="flex">
              <el-link :underline="false" @click="formType = loginForms[0]"
                >登录</el-link
              >
            </div>
          </el-form-item>
        </el-form>
        <el-footer>@依只 2024/3/24</el-footer>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.login-page {
  .el-input {
    // background-color: #66ccff;
  }
  height: 100vh;
  background-repeat: no-repeat;
  .layout {
    height: 100vh;
    // background-color: rgb(248, 247, 247);
    .left {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 55%;
        height: 100%;
        background-color: transparent; /* 透明 */
      }

      img {
        border-radius: 25px;
      }
    }
    .right {
      height: 100%;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      .form {
        width: 80%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
          margin: 0 auto;
          font-style: italic;
          background: linear-gradient(to right, #66ccff 50%, blue 60%);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
        }
        .subBtn {
          width: 100%;
        }
        .code {
          .code-input,
          .code-btn {
            width: 150px;
            height: 75px;
            border: 1.5px solid #ccc;
          }
        }
        .flex {
          width: 100%;
          display: flex;
          justify-content: space-between;
          .el-link {
            font-size: 16px;
          }
        }
      }
      .el-footer {
        position: absolute;
        bottom: 10px; /* 调整 footer 和表单之间的间距 */
      }
    }
  }
}
</style>
